package com.qlmjx.sevalopos;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.qlmjx.sevalopos.Bean.ManageMemberInfo;
import com.qlmjx.sevalopos.Bean.ManagePayInfo;
import com.qlmjx.sevalopos.Bean.MemberBean;
import com.qlmjx.sevalopos.View.BaseDialog;
import com.qlmjx.sevalopos.View.PaySuccessDialog;
import com.qlmjx.sevalopos.adapter.MemAdapter;
import com.qlmjx.sevalopos.base.BaseActivity;
import com.qlmjx.sevalopos.event.AdvEvent;
import com.qlmjx.sevalopos.event.MemEvent;
import com.qlmjx.sevalopos.event.PaystatrEvent;
import com.qlmjx.sevalopos.https.HttpAddress;
import com.qlmjx.sevalopos.https.RequestParams;
import com.qlmjx.sevalopos.utils.ConstantsUtils;
import com.qlmjx.sevalopos.utils.Screensaver;
import com.qlmjx.sevalopos.utils.ViewHolder;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.SharedPreferencesUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.Request;

import static com.qlmjx.sevalopos.MainActivity.hideSoftInput;
import static com.qlmjx.sevalopos.R.id.ed_dj;
import static com.universal.frame.generalutils.DateUtil.starmpToData;

/**
 * Created by sa on 2018/8/3.
 */

public class EatnestActivity extends BaseActivity implements ResultCallBack {
    private EditText ed_yhmc, ed_dj;
    private String TAG = "lzx";
    public PopupWindow MempopupWindow;
    private MemAdapter memAdapter;
    private ListView lv_hy;
    private List<MemberBean> MemberList = new ArrayList<MemberBean>();
    private String saleCustId;
    private int ischoice = 0;
    private TextView tv_cancel, tv_ts,tv_confirm;
    private ImageView iv_erweima;
    private Screensaver SaleScreensaver;
    private String number;
    private PaySuccessDialog paySuccessDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_earnest);

    }

    @Override
    public void initView() {
        ed_yhmc = (EditText) findViewById(R.id.ed_yhmc);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
        tv_ts = (TextView) findViewById(R.id.tv_ts);
        iv_erweima = (ImageView) findViewById(R.id.iv_erweima);
        tv_confirm= (TextView) findViewById(R.id.tv_confirm);
        showPopupWindowMem();
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ischoice = 0;
                ed_yhmc.setText(null);
                tv_cancel.setVisibility(View.GONE);
            }
        });

        ed_yhmc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 3 && ischoice == 0) {
                    String phone = ed_yhmc.getText().toString().trim();
                    getMemInfo(phone);
                }
            }
        });
        ed_dj = (EditText) findViewById(R.id.ed_dj);
        ed_dj.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        ed_dj.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        ed_dj.setText(s);
                        ed_dj.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    ed_dj.setText(s);
                    ed_dj.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        ed_dj.setText(s.subSequence(0, 1));
                        ed_dj.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String yhm = ed_yhmc.getText().toString().trim();
                String dj = ed_dj.getText().toString().trim();
                if (TextUtils.isEmpty(yhm)){
                    ToastUtil.showToast(getApplicationContext(),"客户姓名不能为空！");
                    return;
                }
                if ("0".equals(dj) || TextUtils.isEmpty(dj)||"0.0".equals(dj)||"0.00".equals(dj)||"0.".equals(dj) ){
                    ToastUtil.showToast(getApplicationContext(),"输入的金额不能为0或者空！");
                    return;
                }
                getEatnestInfo(saleCustId,dj);
                tv_confirm.setEnabled(false);
            }
        });
        SaleScreensaver = new Screensaver(10000); //定时5秒
        SaleScreensaver.setOnTimeOutListener(new Screensaver.OnTimeOutListener() {
            @Override
            public void onTimeOut(Screensaver screensaver) {
                getStateInfo(number);
            }
        }); //监听
    }

    /**
     * 查询会员信息
     */
    public void getMemInfo(String phone) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_LOCATIONADMIN, userID
                , new RequestParams(this).getSearchMemberParams(phone)
                , this
                , false, 1);
    }

    /**
     * 生成定金二维码
     */
    public void getEatnestInfo(String customId, String amount) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        Log.i(TAG, "getMemberInfo: " + userID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_EATNEST, userID
                , new RequestParams(this).getEatnestParams(customId, userID, amount)
                , this
                , false, 2);
    }
    //查看支付状态
    public void getStateInfo(String businessNo) {
        String userID = SharedPreferencesUtil.getString(this, ConstantsUtils.USER_ID);
        OKHttpUtils.postAsync(this
                , HttpAddress.SERVICE_PAYSTATE, userID
                , new RequestParams(this).getPayStateParams(businessNo)
                , this
                , false, 3);
    }
    @Override
    public void onSuccess(String response, int flag) {
        try {
            if (flag == 1) {
                getMemIdData(response);
            }
            if (flag == 2) {
                getEatnestData(response);
            }
            if (flag == 3) {
                getStateData(response);
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getApplicationContext(), e);
        }
    }

    private void getEatnestData(String response) {
        String check = JsonUtil.getString(response, "check", "");
        if ("1".equals(check)) {
            iv_erweima.setVisibility(View.VISIBLE);
            tv_ts.setVisibility(View.GONE);
            String image = JsonUtil.getString(response, "image", "");
            number= JsonUtil.getString(response, "number", "");
            Glide.with(this).load(erweima(image)).fitCenter().into(iv_erweima);
            getStateInfo(number);
            SaleScreensaver.start();
        } else {
            iv_erweima.setVisibility(View.GONE);
            tv_ts.setVisibility(View.VISIBLE);
            tv_confirm.setEnabled(true);
            ToastUtil.showToast(getApplicationContext(), "生成二维码失败,请重新提交！");
        }
    }

    private void getMemIdData(String response) {
            ManageMemberInfo info = JSON.parseObject(response, ManageMemberInfo.class);
            if (info.list.size() == 0 || info.list == null) {
                ToastUtil.showToast(this, "会员不存在！");
                if (MempopupWindow.isShowing()) {
                    MempopupWindow.dismiss();
                }
            } else if (info.list.size() > 1) {
                MemberList.clear();
                MemberList.addAll(info.list);
                memAdapter.notifyDataSetChanged();
                MempopupWindow.showAsDropDown(ed_yhmc, 0, 0);
            }

    }
    private void getStateData(String response) {
        String flag = JsonUtil.getString(response, "flag", "");
        if ("0".equals(flag)){
            SaleScreensaver.resetTime();
        }else {
            SaleScreensaver.stop();
            ed_yhmc.setText(null);
            ed_dj.setText(null);
            tv_confirm.setEnabled(true);
            ischoice = 0;
            tv_cancel.setVisibility(View.GONE);
            iv_erweima.setVisibility(View.GONE);
            tv_ts.setVisibility(View.GONE);
            showSuccess();
        }

    }
    //查询会员弹框
    private void showPopupWindowMem() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.huiyuan2, null);
        MempopupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        MempopupWindow.setOutsideTouchable(true);
        MempopupWindow.setBackgroundDrawable(new BitmapDrawable());
        MempopupWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    MempopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        lv_hy = ViewHolder.get(contentview, R.id.lv_hy);
        memAdapter = new MemAdapter(this, MemberList);
        lv_hy.setAdapter(memAdapter);
        lv_hy.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ischoice = 1;
                ed_yhmc.setText(MemberList.get(position).PHONE_NUMBER + "--" + MemberList.get(position).SALE_CUST_NAME);
//                tv_khmc.setText(MemberList.get(position).saleCustName);
                //客户ID
                saleCustId = MemberList.get(position).SALE_CUST_ID;
                tv_cancel.setVisibility(View.VISIBLE);
                ed_yhmc.clearFocus();
                MempopupWindow.dismiss();
                hideSoftInput(EatnestActivity.this, ed_yhmc);

            }
        });
    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {
        tv_confirm.setEnabled(true);
    }
    private byte[] erweima(String base64) {
        Bitmap bitmap = null;
        byte[] bitmapArray;
        bitmapArray = Base64.decode(base64, Base64.DEFAULT);
        bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        return bytes;
    }
    private void showSuccess() {
        paySuccessDialog = new PaySuccessDialog(this, "提示", "恭喜您交付定金成功！", R.style.MyDialogStyle, new BaseDialog.LeaveMyDialogListener() {

            @Override
            public void onClick(View view) {


            }

        });
        paySuccessDialog.show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        SaleScreensaver.stop();
    }
}
